// MagnifierWindow.cpp

#include "magnifierwindow.h"
#include <QPainter>
#include <QMouseEvent>
#include <QGuiApplication>


/**
 * @brief MagnifierWindow::MagnifierWindow
 * @param parent
 * @param value
 * 放大镜窗口
 */


MagnifierWindow::MagnifierWindow(QWidget *parent, qreal value)
    : QWidget(parent), zoomFactor(value)
{
    setupUI();
}

void MagnifierWindow::setupUI()
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setMouseTracking(true);

    QScreen *screen = QGuiApplication::primaryScreen();
    fullScreenPixmap = screen->grabWindow(0);
    resize(fullScreenPixmap.size());
    setCursor(Qt::OpenHandCursor);

    magnifierSize = QSize(100, 50);  // 调整放大镜的大小

    updateTimer = new QTimer(this);
    updateTimer->setInterval(5);
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateMagnifier()));
    //updateTimer->start();
}

void MagnifierWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.drawPixmap(0, 0, fullScreenPixmap);

    painter.setPen(Qt::red);

    // 在鼠标位置绘制放大的局部区域
    QPixmap magnifiedRegion = fullScreenPixmap.copy(
        magnifierPosition.x() - magnifierSize.width() / 2,
        magnifierPosition.y() - magnifierSize.height() / 2,
        magnifierSize.width(),
        magnifierSize.height()
    );

    // 放大局部区域
    magnifiedRegion = magnifiedRegion.scaled(
        magnifierSize.width() * zoomFactor,
        magnifierSize.height() * zoomFactor,
        Qt::KeepAspectRatio
    );

    // 设置放大镜属性
    QPixmap magnifierImage(":/icons/images/magnifier.png"); // 用于表示放大镜的图像文件
    int magnifierWidth = magnifierSize.width() * zoomFactor;
    int magnifierHeight = magnifierSize.height() * zoomFactor;

    // 计算放大镜的位置
    int magnifierX = magnifierPosition.x() - magnifierWidth / 2;
    int magnifierY = magnifierPosition.y() - magnifierHeight / 2;

    // 绘制放大镜
    painter.drawPixmap(magnifierX, magnifierY, magnifierWidth, magnifierHeight, magnifierImage);

    painter.drawPixmap(magnifierPosition, magnifiedRegion);
}

void MagnifierWindow::mouseMoveEvent(QMouseEvent *event)
{
    magnifierPosition = event->pos();
    update();
}

void MagnifierWindow::updateMagnifier()
{
    update();
}

MagnifierWindow::~MagnifierWindow()
{
}
